import os

'''
文件重命名
'''


def renamefile(url, new_st):
    for dirpath, dirnames, filenames, in os.walk(url):
        for filename in filenames:
            try:
                # if not filename.__contains__(last_code):
                #     continue
                inputfilename = os.path.join(dirpath, filename)
                new_filename = new_st + '_' + filename
                outfilename = os.path.join(dirpath, new_filename)
                os.rename(inputfilename, outfilename)
                print("old_name:{}-->new_name:{}".format(inputfilename, outfilename))
            except FileExistsError as f:
                print(f)
                continue


def renamefilebyparentdir(url):
    for dirpath, dirnames, filenames, in os.walk(url):
        for filename in filenames:
            try:
                # if not filename.__contains__(last_code):
                #     continue
                inputfilename = os.path.join(dirpath, filename)
                new_filename = os.path.basename(dirpath) + '_' + filename
                outfilename = os.path.join(dirpath, new_filename)
                os.rename(inputfilename, outfilename)
                print("old_name:{}-->new_name:{}".format(inputfilename, outfilename))
            except FileExistsError as f:
                print(f)
                continue

if __name__ == '__main__':
    url = r'D:\yule\麻酥酥合集 85.3g'
    new_str = "麻酥酥"
    type = 1
    if type == 0:
        renamefile(url, new_str)
    if type == 1:
        renamefilebyparentdir(url)
